package com.vincent.dao.basic;

import java.io.Serializable;
import java.util.List;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

public abstract class BasicDao<T> implements IBasicDAO<T> {

	private Class<T> entityClass;  

	/**
	 * @param t
	 */
	@SuppressWarnings("unchecked")
	public BasicDao() {
		Type genType = getClass().getGenericSuperclass();
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		entityClass = (Class<T>) params[0];
	}

	@Resource
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Override
	public List<T> executeQuery(String hql) {
		// TODO Auto-generated method stub
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> executeQuery(String hql, Object[] parameters) {
		// TODO Auto-generated method stub
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		if (parameters.length > 0 && parameters != null) {
			for (int i = 0; i < parameters.length; i++) {
				query.setParameter(i, parameters[i]);
			}
		}
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getObjectById(Serializable id) {
		// TODO Auto-generated method stub
		return (T) sessionFactory.getCurrentSession().get(entityClass, id);
	}

	@Override
	public Serializable savObject(T t) {
		// TODO Auto-generated method stub
		return sessionFactory.getCurrentSession().save(t);
	}

	@Override
	public void delObject(T t) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().delete(t);
	}

	@Override
	public Object executeQueryUniqueResult(String hql) {
		// TODO Auto-generated method stub
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return query.uniqueResult();
	}

	@Override
	public Object executeQueryUniqueResult(String hql, Object[] parameters) {
		// TODO Auto-generated method stub
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		if (parameters.length > 0 && parameters != null) {
			for (int i = 0; i < parameters.length; i++) {
				query.setParameter(i, parameters[i]);
			}
		}
		return query.uniqueResult();
	}

}
